from threading import Lock
import json


class JSONHelper(object):
    json_helper = None

    def __init__(self, filename):
        self.file = open(filename, 'w+')
        self.lock = Lock()

    @staticmethod
    def create(filename):
        if JSONHelper.json_helper is None:
            JSONHelper.json_helper = JSONHelper(filename)
            return JSONHelper.json_helper
        else:
            return JSONHelper.json_helper

    def write(self, obj):
        try:
            self.lock.acquire()
            obj_str = json.dumps(obj, indent=4)
            self.file.write(obj_str)
        finally:
            self.lock.release()

    def __del__(self):
        self.file.close()